//https://leetcode.cn/problems/duplicate-zeros/

class Solution {
public:
    void duplicateZeros(vector<int>& arr) {
        int cur = 0;
        int dest = -1;

        //找到最后复写的位置
        while (cur < arr.size())
        {
            if (arr[cur])
            {
                dest++;
            }
            else
            {
                dest += 2;
            }
            if (dest >= arr.size() - 1)
                break;
            cur++;
        }

        //判断dest是否越界
        if (dest == arr.size())
        {
            arr[arr.size() - 1] = 0;
            dest -= 2;
            cur--;
        }

        //从后往前复写
        while (cur >= 0)
        {
            if (arr[cur])
            {
                arr[dest--] = arr[cur--];
            }
            else
            {
                arr[dest] = arr[dest - 1] = 0;
                cur--;
                dest -= 2;
            }
        }

    }
};